package com.ssy.lingxi.message.websocket.cluster;

import com.rabbitmq.client.Channel;
import com.ssy.lingxi.message.websocket.model.WsMessage;
import com.ssy.lingxi.message.websocket.session.WsSessionAttr;
import com.ssy.lingxi.message.websocket.session.WsSessionContext;
import com.ssy.lingxi.message.websocket.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.util.List;

/**
 * webSocket消息队列监听类
 * @author yzc
 * @version 2.0.0
 * @date 2021/2/8
 */
@Slf4j
@Component
public class WsMessageListener implements ChannelAwareMessageListener {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @SuppressWarnings("unchecked")
    @Override
    public void onMessage(Message message, Channel channel) {
        List<WsMessage> wsMessageList = (List<WsMessage>) rabbitTemplate.getMessageConverter().fromMessage(message);

        for (WsMessage wsMessage : wsMessageList) {
            String sessionKey = wsMessage.getReceiver();
            log.info("收到rabbitmq消息, sender: {}", sessionKey);
            List<WebSocketSession> webSocketSessions = WsSessionContext.pattern(sessionKey);
            log.info("匹配session key, 得数量: {}", webSocketSessions.size());
            if (CollectionUtils.isEmpty(webSocketSessions)) {
                continue;
            }

            for (WebSocketSession webSocketSession : webSocketSessions) {
                log.info("发送websocket消息, memberId: {}, roleId:{}, userId:{}",
                        webSocketSession.getAttributes().getOrDefault(WsSessionAttr.MEMBER_ID, ""),
                        webSocketSession.getAttributes().getOrDefault(WsSessionAttr.ROLE_ID, ""),
                        webSocketSession.getAttributes().getOrDefault(WsSessionAttr.USER_ID, ""));
                MessageUtil.sendMessage(webSocketSession, wsMessage);
            }
        }
    }
}